package com.jinke.uang.ui.activity.validation;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jinke.uang.R;
import com.jinke.uang.adapter.ContactItemAdapter;
import com.jinke.uang.base.BaseNormalActivity;
import com.jinke.uang.base.BaseResponse;
import com.jinke.uang.common.RouterMap;
import com.jinke.uang.common.NoDoubleClickListener;
import com.jinke.uang.common.UserAuthRouter;
import com.jinke.uang.common.UserInfo;
import com.jinke.uang.constant.Constant;
import com.jinke.uang.bean.AuthUserInfoData;
import com.jinke.uang.constant.HttpConstant;
import com.jinke.uang.model.AuthModule;
import com.jinke.uang.presenter.CommonPresenter;
import com.jinke.uang.bean.ContactItemInfoData;
import com.jinke.uang.bean.DictionaryItemData;
import com.jinke.uang.utils.ToastUtils;
import com.jinke.uang.view.MenuDialog;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 联系人认证
 */
@Route(path = RouterMap.CONTACT_AUTH_PAGE)
//ContactMvpView,
public class ContactAuthActivity extends BaseNormalActivity<CommonPresenter,AuthModule>{

    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.tvNext)
    TextView tvNext;

    @Autowired(name = Constant.IS_BACK)
    boolean is_back;
    private ContactItemAdapter adapter;
    private ArrayList<DictionaryItemData> dictionaryList;
    private MenuDialog mMenuDialog;
    public static String REASONCODE = "orderBackReasonCode";
    private final String COMMON_RELATION = "common_relation";
    private final String  CONTACTS_CODE= "contacts_code";
    private final String RELATION = "4";
    private String reasonCode;

    private List<AuthUserInfoData.ContactsInfoBean.ContactsInfosBean> data = new ArrayList<>();

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        reasonCode = getIntent().getStringExtra(REASONCODE);

        topText.setText(getStringResource(R.string.contact_auth_contact));
        topBack.setOnClickListener(viewclick);
        tvNext.setOnClickListener(viewclick);

    }

    /**
     * 点击信息
     */
    private NoDoubleClickListener viewclick = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            super.onNoDoubleClick(v);
            switch (v.getId()) {
                case R.id.topBack:
                    finish();
                    break;
                case R.id.tvNext:
                    put();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 提交
     */
    private void put() {
        List<ContactItemInfoData> data = new ArrayList<>();
        for (int i = 0; i < rv.getChildCount(); i++) {
            ContactItemInfoData info = new ContactItemInfoData();
            LinearLayout layout = (LinearLayout) rv.getChildAt(i);
            EditText et_name = layout.findViewById(R.id.etName);
            TextView et_phone = layout.findViewById(R.id.etPhone);
            TextView et_relation = layout.findViewById(R.id.etRelation);
            String name = et_name.getText().toString().trim();
            String phone = et_phone.getText().toString().trim();
            String relation = (String) et_relation.getTag();
            if (TextUtils.isEmpty(name)) {
                ToastUtils.showShort(this, getString(R.string.contact_auth_name_toast));
                return;
            } else if (TextUtils.isEmpty(phone)) {
                ToastUtils.showShort(this, getString(R.string.contact_auth_phone_toast));
                return;
            } else if (TextUtils.isEmpty(relation)) {
                ToastUtils.showShort(this, getString(R.string.contact_auth_relation_toast));
                return;
            }
            info.setOrderNo(i + 1 + "");
            info.setUserName(et_name.getText().toString());
            info.setMobile(et_phone.getText().toString());
            info.setRelation((String) et_relation.getTag());
            data.add(info);
        }
        //判断联系人重复
        Set<String> set = new HashSet<>();
        for (ContactItemInfoData itemInfo : data) {
            set.add(itemInfo.getMobile());
        }
        if (set.size() == 5) {
            mPresenter.getData(HttpConstant.UPLOAD_CONTACT_DATA,null,CONTACTS_CODE,data);
            showLoadingView();
        } else {
            ToastUtils.showShort(this, getString(R.string.contact_auth_contact_repeat));
        }
    }

    @Override
    protected void onUIReady() {
        ARouter.getInstance().inject(this);
        mPresenter.getData(HttpConstant.DICTIONARY_DATA,RELATION,COMMON_RELATION);
        LinearLayoutManager lm = new LinearLayoutManager(this);
        rv.setLayoutManager(lm);
        for (int i = 0; i < 5; i++) {
            AuthUserInfoData.ContactsInfoBean.ContactsInfosBean itemInfo = new AuthUserInfoData.ContactsInfoBean.ContactsInfosBean();
            data.add(itemInfo);
        }
        adapter = new ContactItemAdapter(this, data);
        rv.setAdapter(adapter);
        if (UserInfo.isShowUserInformation()) {
            mPresenter.getData(HttpConstant.AUTH_INFO_DATA,null,CONTACTS_CODE);
        }
        if (is_back) {
            tvNext.setText(R.string.save_change);
        }
        adapter.setOnSelectRelationListener(new ContactItemAdapter.OnSelectRelationListener() {
            @Override
            public void onClick(View view, int position) {
                handleDataAndShowDialog((TextView) view);
            }
        });
        adapter.setOnSelectContactListener(new ContactItemAdapter.OnSelectContactListener() {
            @Override
            public void onClick(View view, int position) {

                selectContact(position);
            }
        });
        rv.smoothScrollToPosition(0);
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_auth_contact;
    }

    @Override
    protected int getResId() {
        return 0;
    }

    @Override
    public String getPageTitle() {
        return null;
    }

    @Override
    protected CommonPresenter getPresenter() {
        return new CommonPresenter();
    }

    @Override
    protected AuthModule getModule() {
        return new AuthModule();
    }

    //获取手机联系人
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && (requestCode >= 0 && requestCode <= 4)) {
            Uri uri = data.getData();
            if (uri != null) {
                boolean isOPPO = false;
                Cursor cursor = null;
                try {
                    cursor = getContentResolver().query(uri, new String[]{ContactsContract
                            .CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone
                            .DISPLAY_NAME}, null, null, null);
                    boolean moveToNext = cursor.moveToNext();
                    if (moveToNext) {
                        String number = cursor.getString(0);
                        String name = cursor.getString(1);
                        if (checkContactRepeat(number)) {
                            AuthUserInfoData.ContactsInfoBean.ContactsInfosBean itemInfo =
                                    getItemData(requestCode);
                            itemInfo.setMobile(number);
                            itemInfo.setUserName(name);
                            this.data.set(requestCode, itemInfo);
                            adapter.notifyItemChanged(requestCode);
                        } else {
                            ToastUtils.showShort(this, getString(R.string
                                    .contact_auth_contact_repeat));
                        }
                    } else {
                        isOPPO = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    isOPPO = true;
                } finally {
                    if (cursor != null && !cursor.isClosed()) {
                        cursor.close();
                    }
                }
                if (isOPPO) {
                    adapter.setModel(true);
                    ToastUtils.showShort(this, getString(R.string.contact_auth_phone_hint_enter));
                }
            }
        }
    }

    /**
     * 选择联系人
     *
     * @param request
     */
    public void selectContact(int request) {
        View currentFocus = ((Activity) this).getCurrentFocus();
        if (currentFocus != null) {
            currentFocus.clearFocus();
        }
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
        startActivityForResult(intent, request);
    }

    /**
     * 关系列表展示
     *
     * @param edit_text_relation
     */
    private void handleDataAndShowDialog(TextView edit_text_relation) {
        if (dictionaryList != null && dictionaryList.size() > 0) {
            getMenuDialog().showDialog(edit_text_relation, dictionaryList);
        }
    }

    public MenuDialog getMenuDialog() {
        if (mMenuDialog == null) {
            mMenuDialog = new MenuDialog(this, R.style.dialog_bottom_full);
        }
        return mMenuDialog;
    }

    public AuthUserInfoData.ContactsInfoBean.ContactsInfosBean getItemData(int position) {
        AuthUserInfoData.ContactsInfoBean.ContactsInfosBean info = new AuthUserInfoData.ContactsInfoBean
                .ContactsInfosBean();
        if (rv.getChildCount() - 1 >= position) {
            LinearLayout layout = (LinearLayout) rv.getChildAt(position);
            EditText et_name = layout.findViewById(R.id.etName);
            TextView et_phone = layout.findViewById(R.id.etPhone);
            TextView et_relation = layout.findViewById(R.id.etRelation);
            String name = et_name.getText().toString().trim();
            String phone = et_phone.getText().toString().trim();
            String relation = (String) et_relation.getTag();
            String relationValue = et_relation.getText().toString().trim();
            info.setMobile(phone);
            info.setUserName(name);
            info.setOrderNo(position + 1 + "");
            info.setRelation(relation);
            info.setRelationValue(relationValue);
        }
        return info;
    }

    public boolean checkContactRepeat(String number) {
        for (int i = 0; i < rv.getChildCount(); i++) {
            LinearLayout layout = (LinearLayout) rv.getChildAt(i);
            TextView et_phone = layout.findViewById(R.id.etPhone);
            String phone = et_phone.getText().toString().trim();
            if (number.equals(phone)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void showResponse(int apiType, String listType, Object o) {
        if(apiType== HttpConstant.UPLOAD_CONTACT_DATA){ //通讯录提单认证接口
            dismissLoadingView();
            BaseResponse<String> response = (BaseResponse<String>) o;
            if (response.getStatus() == Constant.HTTP_OK) {
                if (!is_back) {
                    UserAuthRouter.getInstance().jumpNextPager(this, RouterMap.CONTACT_AUTH_PAGE);
                } else {
                    finish();
                }

            } else {
                ToastUtils.showShort(this, response.getMessage());
            }
        }

        else if(apiType==HttpConstant.AUTH_INFO_DATA){//获取联系人认证详情
            BaseResponse<AuthUserInfoData> response = (BaseResponse<AuthUserInfoData>) o;
            for (int index = 0; index < response.getData().getContactsInfo().getContactsInfos().size
                    (); index++) {
                AuthUserInfoData.ContactsInfoBean.ContactsInfosBean info = response.getData()
                        .getContactsInfo().getContactsInfos().get(index);
                data.set(index, info);
            }
            dismissLoadingView();
            adapter.notifyDataSetChanged();
        }

        else if(apiType==HttpConstant.DICTIONARY_DATA){//获取字典关系
            if(listType.equals(RELATION)){
                BaseResponse<ArrayList<DictionaryItemData>> response = (BaseResponse<ArrayList<DictionaryItemData>>) o;
                dictionaryList = response.getData();
            }
        }
    }

    @Override
    public void showError(Throwable e) {
        dismissLoadingView();
        ToastUtils.showShort(this, R.string.network_error);
    }
}
